<!-- src/components/VideoConfigSelect.vue -->
<template>
  <el-dialog
      v-model="dialogVisible"
      :title="props.title || '视频配置'"
      width="900px"
      :close-on-click-modal="false"
      destroy-on-close
  >
    <!-- 配置模式选择 -->
    <div class="mode-selection-container">
      <el-radio-group v-model="configMode" @change="handleModeChange">
        <el-radio-button label="single">单数字人模式</el-radio-button>
        <el-radio-button label="multiple">多数字人模式</el-radio-button>
      </el-radio-group>
      <el-tooltip content="单数字人模式：整篇文章由一个数字人生成；多数字人模式：文章可由多个数字人分段生成或者一篇文章对应一个数字人" placement="top">
        <el-icon class="info-icon"><InfoFilled /></el-icon>
      </el-tooltip>
    </div>

    <!-- 单数字人模式 -->
    <div v-if="configMode === 'single'">
      <el-form
          ref="singleFormRef"
          :model="singleForm"
          :rules="rules"
          label-width="100px"
      >
        <!-- 现有单数字人表单内容（只显示一个公共背景、分辨率等配置） -->
        <el-form-item label="快速配置">
          <el-select
              v-model="selectedConfigId"
              placeholder="选择已有配置"
              clearable
              @change="handleConfigSelect"
              style="width: 100%"
          >
            <el-option
                v-for="item in configList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            >
              <div class="config-option">
                <span>{{ item.name }}</span>
                <el-tag size="small" v-if="item.isDefault" type="success">默认</el-tag>
              </div>
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 虚拟人物选择 -->
        <el-form-item
            label="虚拟人物"
            prop="avatarId"
            :rules="[{ required: true, message: '请选择虚拟人物' }]"
        >
          <div class="select-preview">
            <div v-if="currentAvatar" class="preview-content">
              <el-image
                  :src="currentAvatar.previewImageUrl"
                  class="preview-image"
                  fit="cover"
              >
                <template #error>
                  <div class="image-placeholder">
                    <el-icon><Avatar /></el-icon>
                  </div>
                </template>
              </el-image>
              <div class="preview-info">
                <span>{{ currentAvatar.avatarName }}</span>
                <el-space>
                  <el-tag size="small" :type="getGenderType(currentAvatar.gender)">
                    {{ getGenderLabel(currentAvatar.gender) }}
                  </el-tag>
                  <el-tag size="small" :type="'danger'">
                    {{currentAvatar.premium === true ? '高级版' : '基础版'}}
                  </el-tag>
                </el-space>
              </div>
              <div class="avatar-actions" style="text-align: center">
                <el-button
                    type="primary"
                    link
                    size="small"
                    @click="handlePreview(currentAvatar)"
                >
                  <el-icon><VideoPlay /></el-icon>预览
                </el-button>
              </div>
            </div>
            <el-button @click="showAvatarDialog = true">
              {{ currentAvatar ? '更换' : '选择' }}虚拟人物
            </el-button>
          </div>
        </el-form-item>

        <!-- 人物配置 -->
        <el-form-item label="人物配置">
          <el-collapse>
            <el-collapse-item title="详细配置">
              <div class="avatar-config-form">
                <div class="config-row">
                  <span class="config-label">水平偏移 (X):</span>
                  <el-slider
                      v-model="singleForm.xOffset"
                      :min="-1"
                      :max="1"
                      :step="0.05"
                      show-input
                      :format-tooltip="value => value.toFixed(2)"
                  />
                </div>
                <div class="config-row">
                  <span class="config-label">垂直偏移 (Y):</span>
                  <el-slider
                      v-model="singleForm.yOffset"
                      :min="-1"
                      :max="1"
                      :step="0.05"
                      show-input
                      :format-tooltip="value => value.toFixed(2)"
                  />
                </div>
                <div class="config-row">
                  <span class="config-label">缩放比例:</span>
                  <el-slider
                      v-model="singleForm.scale"
                      :min="0.1"
                      :max="2"
                      :step="0.1"
                      show-input
                      :format-tooltip="value => value.toFixed(2)"
                  />
                </div>
                <div class="avatar-config-tip">
                  <el-alert
                      type="info"
                      :closable="false"
                      show-icon
                  >
                    <template #title>配置建议</template>
                    <div>
                      <p>半身人物建议设置: X: 0.0, Y: 0.25, Scale: 1</p>
                      <p>正值向右/向上偏移，负值向左/向下偏移</p>
                      <p>详细配置请参考 <el-link href="https://docs.heygen.com/page/tools" type="primary" target="_blank">HeyGen文档</el-link></p>
                    </div>
                  </el-alert>
                </div>
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-form-item>

        <!--- 角色语音选择 --->
        <el-form-item
            label="语音"
            prop="voiceId"
            :rules="[{ required: true, message: '请选择语音' }]"
        >
          <div class="select-preview">
            <div v-if="currentVoice" class="preview-content">
              <div class="preview-info">
                <span>{{ currentVoice.name }}</span>
                <div class="preview-tags">
                  <el-tag size="small" type="success">{{ getLanguageLabel(currentVoice.language) }}</el-tag>
                  <el-tag size="small" :type="getGenderType(currentVoice.gender)">
                    {{ getGenderLabel(currentVoice.gender) }}
                  </el-tag>
                </div>
              </div>
              <el-button
                  link
                  type="primary"
                  @click="handlePreviewVoice"
                  :disabled="!currentVoice.previewAudio"
              >试听</el-button>
            </div>
            <el-button @click="showVoiceDialog = true">
              {{ currentVoice ? '更换' : '选择' }}语音
            </el-button>
          </div>
        </el-form-item>

        <!-- 单数字人模式下的公共配置 -->
        <div class="common-settings">
          <el-divider content-position="center">公共配置</el-divider>
          <!-- 背景和分辨率配置 -->
          <el-form-item label="背景类型">
            <el-radio-group v-model="singleForm.backgroundType" @change="handleBackgroundTypeChange">
              <el-radio label="color">颜色背景</el-radio>
              <el-radio label="image">图片背景</el-radio>
              <el-radio label="video">视频背景</el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 颜色背景 -->
          <el-form-item v-if="singleForm.backgroundType === 'color'" label="背景颜色">
            <el-color-picker v-model="singleForm.backgroundColor" />
          </el-form-item>

          <!-- 图片/视频背景 -->
          <template v-if="singleForm.backgroundType === 'image' || singleForm.backgroundType === 'video'">
            <!-- 背景资源选择 -->
            <el-form-item :label="singleForm.backgroundType === 'image' ? '背景图片' : '背景视频'">
              <div class="background-resource-container">
                <!-- 已选择的背景预览 -->
                <div v-if="singleForm.backgroundUrl" class="background-preview">
                  <el-image
                      v-if="singleForm.backgroundType === 'image'"
                      :src="singleForm.backgroundUrl"
                      class="preview-image"
                      fit="cover"
                  ></el-image>
                  <video
                      v-else
                      :src="singleForm.backgroundUrl"
                      class="preview-video"
                      autoplay
                      loop
                      muted
                  ></video>
                  <el-button
                      class="remove-btn"
                      type="danger"
                      circle
                      @click="removeBackground"
                      size="small"
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>

                <!-- 操作按钮 -->
                <div v-if="!singleForm.backgroundUrl" class="background-actions">
                  <el-button type="primary" @click="showBackgroundGallery = true">
                    从库中选择
                  </el-button>
                  <el-upload
                      :action="getUploadUrl()"
                      :headers="{ 'Authorization': 'Bearer ' + getToken() }"
                      :on-success="handleUploadSuccess"
                      :on-error="handleUploadError"
                      :before-upload="beforeBackgroundUpload"
                      :on-progress="handleUploadProgress"
                      :show-file-list="false"
                      :accept="singleForm.backgroundType === 'image' ? 'image/jpeg,image/png' : 'video/mp4,video/webm'"
                      :data="{ fileType: singleForm.backgroundType }"
                  >
                    <el-button type="primary" :loading="isUploading">
                      {{ isUploading ? '上传中...' : '上传新' + (singleForm.backgroundType === 'image' ? '图片' : '视频') }}
                    </el-button>
                  </el-upload>
                </div>
              </div>
            </el-form-item>

            <!-- 背景适配方式 -->
            <el-form-item label="适配方式">
              <el-select v-model="singleForm.backgroundFit" style="width: 120px">
                <el-option label="裁剪" value="crop"></el-option>
                <el-option label="覆盖" value="cover"></el-option>
                <el-option label="包含" value="contain"></el-option>
                <el-option label="无" value="none"></el-option>
              </el-select>
            </el-form-item>

            <!-- 视频播放方式 -->
            <el-form-item v-if="singleForm.backgroundType === 'video'" label="播放方式">
              <el-select v-model="singleForm.backgroundPlayStyle" style="width: 120px">
                <el-option label="循环" value="loop"></el-option>
                <el-option label="单次" value="once"></el-option>
                <el-option label="适合场景" value="fit_to_scene"></el-option>
                <el-option label="不循环" value="freeze"></el-option>
              </el-select>
            </el-form-item>
          </template>

          <!-- 分辨率 -->
          <el-form-item label="分辨率">
            <el-select v-model="singleForm.resolution" placeholder="选择分辨率" label="分辨率" @change="handleResolutionChange('single')" style="width: 120px">
              <el-option label="竖屏" value="1080x1920"></el-option>
              <el-option label="横屏" value="1280x720"></el-option>
            </el-select>
          </el-form-item>

          <!-- 保存为配置 -->
          <el-form-item>
            <el-checkbox v-model="saveAsConfig">保存为新配置</el-checkbox>
            <el-checkbox v-model="singleForm.isCaption" class="ml-3">开启字幕</el-checkbox>
          </el-form-item>

          <!-- 配置名称 -->
          <el-form-item
              v-if="saveAsConfig"
              label="配置名称"
              prop="name"
              :rules="[
                { required: true, message: '请输入配置名称' },
                { min: 2, max: 20, message: '长度在 2 到 20 个字符' }
              ]"
          >
            <el-input v-model="singleForm.name" placeholder="请输入配置名称" />
            <el-checkbox v-model="singleForm.isDefault" class="mt-2">设为默认配置</el-checkbox>
          </el-form-item>
        </div>
      </el-form>
    </div>

    <!-- 多数字人模式 -->
    <div v-else class="multi-avatar-container">
      <el-form-item label="快速配置">
        <el-select
            v-model="selectedMultiConfigId"
            placeholder="选择已有配置"
            clearable
            @change="handleMultiConfigSelect"
            style="width: 100%"
        >
          <el-option
              v-for="item in multiconfigList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          >
            <div class="config-option">
              <span>{{ item.name }}</span>
              <el-tag size="small" v-if="item.isDefault" type="success">默认</el-tag>
            </div>
          </el-option>
        </el-select>
      </el-form-item>
      <!-- 公共配置部分 -->
      <div class="common-settings">
        <h3>公共配置</h3>
        <el-form
            ref="multiCommonFormRef"
            :model="multiCommonForm"
            label-width="100px"
        >
          <!-- 背景类型选择 -->
          <el-form-item label="背景类型">
            <el-radio-group v-model="multiCommonForm.backgroundType" @change="handleMultiBackgroundTypeChange">
              <el-radio label="color">颜色背景</el-radio>
              <el-radio label="image">图片背景</el-radio>
              <el-radio label="video">视频背景</el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 颜色背景 -->
          <el-form-item v-if="multiCommonForm.backgroundType === 'color'" label="背景颜色">
            <el-color-picker v-model="multiCommonForm.backgroundColor" />
          </el-form-item>

          <!-- 图片/视频背景 -->
          <template v-if="multiCommonForm.backgroundType === 'image' || multiCommonForm.backgroundType === 'video'">
            <!-- 背景资源选择 -->
            <el-form-item :label="multiCommonForm.backgroundType === 'image' ? '背景图片' : '背景视频'">
              <div class="background-resource-container">
                <!-- 多背景管理部分 -->
                <div class="multi-background-container">
                  <div v-if="multiBackgrounds.length === 0" class="empty-background-tip">
                    <el-alert
                        title="请添加至少一个背景"
                        type="info"
                        description="您可以添加多个背景，每个数字人将按顺序使用不同背景。如果背景数量少于数字人数量，背景将循环使用。"
                        :closable="false"
                        show-icon
                    />
                  </div>

                  <!-- 背景列表 -->
                  <div class="background-list">
                    <!-- 已添加的背景 -->
                    <div v-for="(bg, index) in multiBackgrounds" :key="index" class="background-item">
                      <div class="background-preview">
                        <el-image
                            v-if="multiCommonForm.backgroundType === 'image'"
                            :src="bg.url"
                            class="preview-image"
                            fit="cover"
                        ></el-image>
                        <video
                            v-else
                            :src="bg.url"
                            class="preview-video"
                            autoplay
                            loop
                            muted
                        ></video>
                      </div>
                      <!-- 将删除按钮移到background-preview外部，确保它不会被内部元素遮挡 -->
                      <el-button
                          class="remove-btn"
                          type="danger"
                          circle
                          @click="removeMultiBackgroundItem(index)"
                          size="small"
                      >
                        <el-icon><Delete /></el-icon>
                      </el-button>
                      <div class="background-index">背景 #{{ index + 1 }}</div>
                    </div>
                  </div>

                  <!-- 添加背景按钮区域 -->
                  <div class="add-background-container">
                    <el-button @click="showMultiBackgroundGallery = true" class="add-background-btn" type="primary">
                      <el-icon><Plus /></el-icon> 从库中选择背景
                    </el-button>
                    <el-upload
                        :action="getUploadUrl()"
                        :headers="{ 'Authorization': 'Bearer ' + getToken() }"
                        :on-success="handleMultiUploadSuccess"
                        :on-error="handleUploadError"
                        :before-upload="beforeMultiBackgroundUpload"
                        :on-progress="handleUploadProgress"
                        :show-file-list="false"
                        :accept="multiCommonForm.backgroundType === 'image' ? 'image/jpeg,image/png' : 'video/mp4,video/webm'"
                        :data="{ fileType: multiCommonForm.backgroundType }"
                    >
                      <el-button :loading="isUploading" type="primary">
                        {{ isUploading ? '上传中...' : '上传' + (multiCommonForm.backgroundType === 'image' ? '图片' : '视频') }}
                      </el-button>
                    </el-upload>
                  </div>
                </div>
              </div>
            </el-form-item>

            <!-- 背景适配方式 -->
            <el-form-item label="适配方式">
              <el-select v-model="multiCommonForm.backgroundFit" style="width: 120px">
                <el-option label="裁剪" value="crop"></el-option>
                <el-option label="覆盖" value="cover"></el-option>
                <el-option label="包含" value="contain"></el-option>
                <el-option label="无" value="none"></el-option>
              </el-select>
            </el-form-item>

            <!-- 视频播放方式 -->
            <el-form-item v-if="multiCommonForm.backgroundType === 'video'" label="播放方式">
              <el-select v-model="multiCommonForm.backgroundPlayStyle" style="width: 120px">
                <el-option label="循环" value="loop"></el-option>
                <el-option label="单次" value="once"></el-option>
                <el-option label="适合场景" value="fit_to_scene"></el-option>
                <el-option label="不循环" value="freeze"></el-option>
              </el-select>
            </el-form-item>
          </template>

          <!-- 分辨率 -->
          <el-form-item label="分辨率">
            <el-select v-model="multiCommonForm.resolution" placeholder="选择分辨率" @change="handleResolutionChange('multi')" style="width: 120px">
              <el-option label="竖屏" value="1080x1920"></el-option>
              <el-option label="横屏" value="1280x720"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-checkbox v-model="multiCommonForm.isCaption">开启字幕</el-checkbox>
            <el-checkbox v-model="multiCommonForm.one_to_one">一对一模式</el-checkbox>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数字人配置列表 -->
      <div class="avatar-list-container">
        <h3>数字人配置
          <el-button type="primary" size="small" @click="addAvatarConfig" plain round>
            <el-icon><Plus /></el-icon> 添加数字人
          </el-button>
        </h3>

        <div v-if="multiAvatarConfigs.length === 0" class="empty-avatar-list">
          <el-empty description="请添加至少一个数字人配置" />
        </div>

        <el-collapse v-else v-model="activeAvatarPanels">
          <el-collapse-item
              v-for="(avatarConfig, index) in multiAvatarConfigs"
              :key="index"
              :name="index.toString()"
          >
            <template #title>
              <div class="avatar-collapse-title">
                <span v-if="avatarConfig.avatar">{{ avatarConfig.avatar.avatarName }}</span>
                <span v-else>数字人 #{{ index + 1 }}</span>
                <span class="content-preview" v-if="avatarConfig.content">
                  {{ avatarConfig.content.length > 20 ? avatarConfig.content.substring(0, 20) + '...' : avatarConfig.content }}
                </span>
              </div>
            </template>

            <el-form
                :ref="el => { if (el) multiAvatarFormRefs[index] = el }"
                :model="avatarConfig"
                label-width="100px"
            >
              <!-- 虚拟人物选择 -->
              <el-form-item label="虚拟人物" required>
                <div class="select-preview">
                  <div v-if="avatarConfig.avatar" class="preview-content">
                    <el-image
                        :src="avatarConfig.avatar.previewImageUrl"
                        class="preview-image"
                        fit="cover"
                    >
                      <template #error>
                        <div class="image-placeholder">
                          <el-icon><Avatar /></el-icon>
                        </div>
                      </template>
                    </el-image>
                    <div class="preview-info">
                      <span>{{ avatarConfig.avatar.avatarName }}</span>
                      <el-space>
                        <el-tag size="small" :type="getGenderType(avatarConfig.avatar.gender)">
                          {{ getGenderLabel(avatarConfig.avatar.gender) }}
                        </el-tag>
                        <el-tag size="small" :type="'danger'">
                          {{avatarConfig.avatar.premium === true ? '高级版' : '基础版'}}
                        </el-tag>
                      </el-space>
                    </div>
                    <div class="avatar-actions" style="text-align: center">
                      <el-button
                          type="primary"
                          link
                          size="small"
                          @click="handlePreviewMulti(avatarConfig.avatar)"
                      >
                        <el-icon><VideoPlay /></el-icon>预览
                      </el-button>
                    </div>
                  </div>
                  <el-button @click="showMultiAvatarDialog(index)">
                    {{ avatarConfig.avatar ? '更换' : '选择' }}虚拟人物
                  </el-button>
                </div>
              </el-form-item>

              <!-- 人物配置 -->
              <el-form-item label="人物配置">
                <el-collapse>
                  <el-collapse-item title="详细配置">
                    <div class="avatar-config-form">
                      <div class="config-row">
                        <span class="config-label">水平偏移 (X):</span>
                        <el-slider
                            v-model="avatarConfig.xOffset"
                            :min="-1"
                            :max="1"
                            :step="0.05"
                            show-input
                            :format-tooltip="value => value.toFixed(2)"
                        />
                      </div>
                      <div class="config-row">
                        <span class="config-label">垂直偏移 (Y):</span>
                        <el-slider
                            v-model="avatarConfig.yOffset"
                            :min="-1"
                            :max="1"
                            :step="0.05"
                            show-input
                            :format-tooltip="value => value.toFixed(2)"
                        />
                      </div>
                      <div class="config-row">
                        <span class="config-label">缩放比例:</span>
                        <el-slider
                            v-model="avatarConfig.scale"
                            :min="0.1"
                            :max="2"
                            :step="0.1"
                            show-input
                            :format-tooltip="value => value.toFixed(2)"
                        />
                      </div>
                    </div>
                  </el-collapse-item>
                </el-collapse>
              </el-form-item>

              <!--- 角色语音选择 --->
              <el-form-item label="语音" required>
                <div class="select-preview">
                  <div v-if="avatarConfig.voice" class="preview-content">
                    <div class="preview-info">
                      <span>{{ avatarConfig.voice.name }}</span>
                      <div class="preview-tags">
                        <el-tag size="small" type="success">{{ getLanguageLabel(avatarConfig.voice.language) }}</el-tag>
                        <el-tag size="small" :type="getGenderType(avatarConfig.voice.gender)">
                          {{ getGenderLabel(avatarConfig.voice.gender) }}
                        </el-tag>
                      </div>
                    </div>
                    <el-button
                        link
                        type="primary"
                        @click="handlePreviewMultiVoice(index)"
                        :disabled="!avatarConfig.voice.previewAudio"
                    >试听</el-button>
                  </div>
                  <el-button @click="showMultiVoiceDialog(index)">
                    {{ avatarConfig.voice ? '更换' : '选择' }}语音
                  </el-button>
                </div>
              </el-form-item>

              <!-- 操作按钮 -->
              <el-form-item>
                <el-button type="danger" @click="removeAvatarConfig(index)" plain size="small">
                  <el-icon><Delete /></el-icon> 删除此数字人
                </el-button>
              </el-form-item>
            </el-form>

            <!-- 分隔线 -->
            <el-divider v-if="index < multiAvatarConfigs.length - 1"></el-divider>
          </el-collapse-item>
        </el-collapse>
      </div>
    </div>

    <!-- 弹窗底部按钮 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="handleConfirm" :loading="props.submitting">
          确定
        </el-button>
      </div>
    </template>

    <!-- 虚拟人物选择弹窗 -->
    <el-dialog
        v-model="showAvatarDialog"
        title="选择虚拟人物"
        width="900px"
        append-to-body
    >
      <AvatarList @select="handleAvatarSelect" />
    </el-dialog>

    <!-- 多数字人模式下的虚拟人物选择弹窗 -->
    <el-dialog
        v-model="showMultiAvatarDialogVisible"
        title="选择虚拟人物"
        width="900px"
        append-to-body
    >
      <AvatarList @select="handleMultiAvatarSelect" />
    </el-dialog>

    <!-- 语音选择弹窗 -->
    <el-dialog
        v-model="showVoiceDialog"
        title="选择语音"
        width="900px"
        append-to-body
    >
      <VoiceList @select="handleVoiceSelect" />
    </el-dialog>

    <!-- 多数字人模式下的语音选择弹窗 -->
    <el-dialog
        v-model="showMultiVoiceDialogVisible"
        title="选择语音"
        width="900px"
        append-to-body
    >
      <VoiceList @select="handleMultiVoiceSelect" />
    </el-dialog>

    <!-- 背景资源库选择弹窗 -->
    <el-dialog
        v-model="showBackgroundGallery"
        :title="singleForm.backgroundType === 'image' ? '选择背景图片' : '选择背景视频'"
        width="900px"
        append-to-body
    >
      <BackgroundGallery
          :type="singleForm.backgroundType"
          @select="handleBackgroundSelect"
      />
    </el-dialog>

    <!-- 多数字人模式下的背景资源库选择弹窗 -->
    <el-dialog
        v-model="showMultiBackgroundGallery"
        :title="multiCommonForm.backgroundType === 'image' ? '选择背景图片' : '选择背景视频'"
        width="900px"
        append-to-body
    >
      <BackgroundGallery
          :type="multiCommonForm.backgroundType"
          @select="handleMultiBackgroundSelect"
      />
    </el-dialog>
  </el-dialog>

  <!-- 试听音频播放器 -->
  <audio
      ref="audioPlayer"
      @ended="handleAudioEnd"
      style="display: none"
  ></audio>

  <!-- 预览弹窗 -->
  <el-dialog
      v-model="previewDialog.visible"
      title="虚拟人物预览"
      width="630"
      :close-on-click-modal="false"
  >
    <video
        width="600"
        v-if="previewDialog.videoUrl"
        :src="previewDialog.videoUrl"
        controls
        class="preview-video"
    ></video>
  </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted, reactive, watch, nextTick } from 'vue'
import { Avatar, Delete, VideoPlay, InfoFilled, Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useConfigStore } from '@/stores/video/config'
import AvatarList from '@/components/AvatarSelect.vue'
import VoiceList from '@/components/VoiceSelect.vue'
import BackgroundGallery from '@/components/BackgroundGallery.vue'
import { useAvatarStore } from '@/stores/video/avatar'
import { useVoiceStore } from '@/stores/video/voice'
import { useBackgroundStore } from '@/stores/video/background'
import { getGenderLabel, getGenderType, getLanguageLabel } from "../utils/label.js"
import { getToken } from "@/utils/auth.js"
import { getUploadUrl } from "@/utils/uploadConfig.js"

// 上传状态
const isUploading = ref(false)
const uploadProgress = ref(0)

// 配置模式（单数字人或多数字人）
const configMode = ref('single')

// 单数字人模式相关变量
const singleFormRef = ref(null)
const currentAvatar = ref(null)
const currentVoice = ref(null)
const selectedConfigId = ref('')
const selectedMultiConfigId = ref('')

// 多数字人模式相关变量
const multiCommonFormRef = ref(null)
const multiAvatarFormRefs = ref({})
const activeAvatarPanels = ref(['0']) // 默认展开第一个面板
const currentMultiAvatarIndex = ref(0)
const showMultiAvatarDialogVisible = ref(false)
const showMultiVoiceDialogVisible = ref(false)
const showMultiBackgroundGallery = ref(false)

// 音频播放状态
const isPlaying = ref(false)

// 多数字人配置数组
const multiAvatarConfigs = ref([])
// 新增变量: 多背景管理
const multiBackgrounds = ref([]);

// 属性定义
const props = defineProps({
  visible: Boolean,
  title: String,
  defaultConfig: Object,
  multiConfig: Object,
  loading: {
    type: Boolean,
    default: false
  },
  submitting: Boolean,
  article: Object // 添加文章属性以便于拆分内容
})

// 预览弹窗
const previewDialog = reactive({
  visible: false,
  videoUrl: ''
})

// 事件定义
const emit = defineEmits(['update:visible', 'confirm'])

// 状态管理
const configStore = useConfigStore()
const avatarStore = useAvatarStore()
const voiceStore = useVoiceStore()
const backgroundStore = useBackgroundStore()

// 响应式数据
const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

const configList = ref([])
const multiconfigList = ref([])
// 控制弹窗显示
const showAvatarDialog = ref(false)
const showVoiceDialog = ref(false)
const showBackgroundGallery = ref(false)

const audioPlayer = ref(null)
const saveAsConfig = ref(false)

// 单数字人表单数据
const singleForm = ref({
  id: '',
  name: '',
  avatarId: '',
  voiceId: '',
  // 人物配置
  xOffset: 0.03,
  yOffset: 0.13,
  scale: 1.4,
  // 背景相关属性
  backgroundType: 'color',
  backgroundId: '',
  backgroundColor: '#f6f6fc',
  backgroundUrl: '',
  backgroundFit: 'crop',
  backgroundPlayStyle: 'loop',
  width: 1080,
  height: 1920,
  isDefault: false,
  isCaption: false,
  resolution: '1080x1920'
})

// 多数字人公共表单数据
const multiCommonForm = ref({
  backgroundType: 'color',
  backgroundId: '',
  backgroundUrl: '',
  backgroundUrls: [],
  backgroundIds: [],
  backgroundColor: '#f6f6fc',
  backgroundFit: 'crop',
  backgroundPlayStyle: 'loop',
  width: 1080,
  height: 1920,
  isCaption: false,
  one_to_one: true,
  resolution: '1080x1920'
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入配置名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  avatarId: [
    { required: true, message: '请选择虚拟人物', trigger: 'change' }
  ],
  voiceId: [
    { required: true, message: '请选择语音', trigger: 'change' }
  ]
}

// 处理模式切换
const handleModeChange = (mode) => {
  if (mode === 'multiple' && multiAvatarConfigs.value.length === 0) {
    // 首次切换到多数字人模式，添加一个默认配置
    addAvatarConfig()
  }
}

// 添加数字人配置
const addAvatarConfig = () => {
  multiAvatarConfigs.value.push({
    avatarId: '',
    voiceId: '',
    avatar: null,
    voice: null,
    xOffset: 0.03,
    yOffset: 0.13,
    scale: 1.4,
    content: ''
  })

  // 自动打开新添加的面板
  nextTick(() => {
    activeAvatarPanels.value = [(multiAvatarConfigs.value.length - 1).toString()]
  })
}

// 删除数字人配置
const removeAvatarConfig = (index) => {
  multiAvatarConfigs.value.splice(index, 1)
}

// 显示多数字人模式下的虚拟人物选择弹窗
const showMultiAvatarDialog = (index) => {
  currentMultiAvatarIndex.value = index
  showMultiAvatarDialogVisible.value = true
}

// 显示多数字人模式下的语音选择弹窗
const showMultiVoiceDialog = (index) => {
  currentMultiAvatarIndex.value = index
  showMultiVoiceDialogVisible.value = true
}

// 处理多数字人模式下的虚拟人物选择
const handleMultiAvatarSelect = (avatar) => {
  const index = currentMultiAvatarIndex.value
  multiAvatarConfigs.value[index].avatar = avatar
  multiAvatarConfigs.value[index].avatarId = avatar.avatarId
  showMultiAvatarDialogVisible.value = false
}

// 处理多数字人模式下的语音选择
const handleMultiVoiceSelect = (voice) => {
  const index = currentMultiAvatarIndex.value
  multiAvatarConfigs.value[index].voice = voice
  multiAvatarConfigs.value[index].voiceId = voice.voiceId
  showMultiVoiceDialogVisible.value = false
}

// 处理多数字人模式下的语音预览
const handlePreviewMultiVoice = async (index) => {
  const voice = multiAvatarConfigs.value[index].voice
  if (!voice?.previewAudio) {
    ElMessage.warning('暂无试听音频')
    return
  }

  // 如果当前正在播放，则停止播放
  if (isPlaying.value) {
    stopAudio()
    return
  }

  // 验证音频URL
  if (!isValidAudioUrl(voice.previewAudio)) {
    ElMessage.error('无效的音频文件地址')
    return
  }

  try {
    // 设置音频源并播放
    audioPlayer.value.src = voice.previewAudio
    await audioPlayer.value.play()
    isPlaying.value = true
  } catch (err) {
    console.error('Audio playback failed:', err)
  }
}

// 多数字人模式下的人物预览
const handlePreviewMulti = (avatar) => {
  if (!avatar.previewVideoUrl) {
    ElMessage.warning('暂无预览视频')
    return
  }
  previewDialog.videoUrl = avatar.previewVideoUrl
  previewDialog.visible = true
}

// 处理背景类型变化（单数字人模式）
const handleBackgroundTypeChange = (type) => {
  // 清空之前的背景设置
  if (type === 'color') {
    singleForm.value.backgroundUrl = ''
    singleForm.value.backgroundId = ''
  } else if (type === 'image' || type === 'video') {
    singleForm.value.backgroundColor = ''
    singleForm.value.backgroundUrl = ''
    singleForm.value.backgroundId = ''
  }
}

// 处理背景类型变化（多数字人模式）
const handleMultiBackgroundTypeChange = (type) => {
  // 清空之前的背景设置
  if (type === 'color') {
    multiCommonForm.value.backgroundUrl = ''
    multiCommonForm.value.backgroundId = ''
  } else if (type === 'image' || type === 'video') {
    multiCommonForm.value.backgroundColor = ''
    multiCommonForm.value.backgroundUrl = ''
    multiCommonForm.value.backgroundId = ''
  }
}

// 从背景选择处理（单数字人模式）
const handleBackgroundSelect = (background) => {
  singleForm.value.backgroundUrl = background.url
  singleForm.value.backgroundId = background.id
  showBackgroundGallery.value = false
}

// 处理多背景选择
const handleMultiBackgroundSelect = (background) => {
  multiBackgrounds.value.push({
    id: background.id,
    url: background.url
  });
  updateMultiCommonFormBackgrounds(); // 更新公共配置中的背景列表
  showMultiBackgroundGallery.value = false;
}

// 移除已选背景（单数字人模式）
const removeBackground = () => {
  singleForm.value.backgroundUrl = ''
  singleForm.value.backgroundId = ''
}

// 移除所有多背景
const removeMultiBackground = () => {
  multiBackgrounds.value = [];
  multiCommonForm.value.backgroundUrls = [];
  multiCommonForm.value.backgroundIds = [];
  multiCommonForm.value.backgroundUrl = '';
  multiCommonForm.value.backgroundId = '';
}

// 移除特定背景项
const removeMultiBackgroundItem = (index) => {
  multiBackgrounds.value.splice(index, 1);
  updateMultiCommonFormBackgrounds(); // 更新公共配置中的背景列表
}

// 上传前验证（单数字人模式）
const beforeBackgroundUpload = (file) => {
  return validateUpload(file, singleForm.value.backgroundType)
}

// 上传前验证（多数字人模式）
const beforeMultiBackgroundUpload = (file) => {
  return validateUpload(file, multiCommonForm.value.backgroundType)
}

// 验证上传文件
const validateUpload = (file, backgroundType) => {
  // 重置上传状态
  isUploading.value = true
  uploadProgress.value = 0

  // 允许的MIME类型列表
  const allowedImageTypes = ['image/jpeg', 'image/png']
  const allowedVideoTypes = ['video/mp4', 'video/webm']

  // 根据当前选择的背景类型进行验证
  if (backgroundType === 'image') {
    if (!allowedImageTypes.includes(file.type)) {
      isUploading.value = false
      ElMessage.error('背景图片只能是 JPG 或 PNG 格式!')
      return false
    }
  } else if (backgroundType === 'video') {
    if (!allowedVideoTypes.includes(file.type)) {
      isUploading.value = false
      ElMessage.error('背景视频只能是 MP4 或 WEBM 格式!')
      return false
    }
  }

  // 文件大小验证 (50MB)
  const maxSize = 50 * 1024 * 1024
  if (file.size > maxSize) {
    isUploading.value = false
    ElMessage.error('文件大小不能超过 50MB!')
    return false
  }

  return true
}

// 文件上传进度处理
const handleUploadProgress = (event) => {
  isUploading.value = true
  if (event.total > 0) {
    uploadProgress.value = Math.round((event.loaded / event.total) * 100)
  }
}

// 上传成功处理（单数字人模式）
const handleUploadSuccess = (response) => {
  isUploading.value = false
  uploadProgress.value = 100

  if (response.code === 200 && response.data) {
    singleForm.value.backgroundUrl = response.data.url
    singleForm.value.backgroundId = response.data.id

    // 刷新背景资源库数据
    backgroundStore.getBackgrounds({
      page: 1,
      pageSize: 12,
      type: singleForm.value.backgroundType
    })

    ElMessage.success('上传成功')
  } else {
    ElMessage.error(response.message || '上传失败')
  }
}

// 上传多背景成功处理
const handleMultiUploadSuccess = (response) => {
  isUploading.value = false;
  uploadProgress.value = 100;

  if (response.code === 200 && response.data) {
    // 添加到多背景列表
    multiBackgrounds.value.push({
      id: response.data.id,
      url: response.data.url
    });
    updateMultiCommonFormBackgrounds(); // 更新公共配置中的背景列表

    // 刷新背景资源库数据
    backgroundStore.getBackgrounds({
      page: 1,
      pageSize: 12,
      type: multiCommonForm.value.backgroundType
    });

    ElMessage.success('上传成功');
  } else {
    ElMessage.error(response.message || '上传失败');
  }
}

// 更新公共配置中的背景列表
const updateMultiCommonFormBackgrounds = () => {
  // 将多背景信息更新到公共配置对象中
  multiCommonForm.value.backgroundUrls = multiBackgrounds.value.map(bg => bg.url);
  multiCommonForm.value.backgroundIds = multiBackgrounds.value.map(bg => bg.id);

  // 如果有背景，同时更新单一背景字段用于兼容
  if (multiBackgrounds.value.length > 0) {
    multiCommonForm.value.backgroundUrl = multiBackgrounds.value[0].url;
    multiCommonForm.value.backgroundId = multiBackgrounds.value[0].id;
  } else {
    multiCommonForm.value.backgroundUrl = '';
    multiCommonForm.value.backgroundId = '';
  }
}

// 上传失败处理
const handleUploadError = (e) => {
  isUploading.value = false
  uploadProgress.value = 0
  ElMessage.error('上传失败，请稍后重试')
}

// 处理分辨率变化
function handleResolutionChange(mode, value) {
  const resolution = mode === 'single' ? singleForm.value.resolution : multiCommonForm.value.resolution
  const [width, height] = resolution.split('x').map(Number)

  if (mode === 'single') {
    singleForm.value.width = width
    singleForm.value.height = height
  } else {
    multiCommonForm.value.width = width
    multiCommonForm.value.height = height
  }
}

// 处理虚拟人物选择（单数字人模式）
const handleAvatarSelect = (avatar) => {
  currentAvatar.value = avatar
  singleForm.value.avatarId = avatar.avatarId
  showAvatarDialog.value = false
}

// 处理语音选择（单数字人模式）
const handleVoiceSelect = (voice) => {
  currentVoice.value = voice
  singleForm.value.voiceId = voice.voiceId
  showVoiceDialog.value = false
}

// 修改关闭对话框的方法
const closeDialog = () => {
  stopAudio() // 停止音频播放
  resetForm() // 重置表单
  emit('update:visible', false) // 触发更新visible的事件
}

// 初始化方法
const init = async () => {
  // 加载配置列表
  await configStore.getDefault()
  configList.value = configStore.defaultConfigs

  await configStore.getMulti()
  multiconfigList.value = configStore.multiConfigs

  // 确保multiCommonForm包含多背景相关字段
  multiCommonForm.value = {
    ...multiCommonForm.value,
    backgroundUrls: [],
    backgroundIds: []
  };
}

// 处理配置选择
const handleConfigSelect = async (configId) => {
  if (!configId) {
    resetForm()
    return
  }

  const config = configList.value.find(c => c.id === configId)
  if (config) {
    // 只复制需要的属性
    singleForm.value = {
      id: config.id || null,
      name: config.name || '',
      avatarId: config.avatarId || '',
      voiceId: config.voiceId || '',

      // 人物配置
      xOffset: config.xOffset !== undefined ? config.xOffset : 0.03,
      yOffset: config.yOffset !== undefined ? config.yOffset : 0.13,
      scale: config.scale !== undefined ? config.scale : 1.4,

      // 背景相关属性
      backgroundType: config.backgroundType || 'color',
      backgroundId: config.backgroundId || '',
      backgroundColor: config.backgroundColor || '#f6f6fc',
      backgroundUrl: config.backgroundUrl || '',
      backgroundFit: config.backgroundFit || 'crop',
      backgroundPlayStyle: config.backgroundPlayStyle,

      width: config.width || 1280,
      height: config.height || 720,
      isDefault: config.isDefault || false,
      isCaption: config.isCaption || false,
      resolution: `${config.width}x${config.height}`
    }
    currentAvatar.value = await loadAvatarInfo(config.avatarId)
    currentVoice.value = await loadVoiceInfo(config.voiceId)
  }
}

// 处理多数字人配置选择
const handleMultiConfigSelect = async (configId) => {
  if (!configId) {
    resetForm()
    return
  }

  const config = multiconfigList.value.find(c => c.id === configId)
  if (config) {
    // 只复制需要的属性
    multiCommonForm.value = {
      backgroundType: config.backgroundType,
      backgroundId: config.backgroundId,
      backgroundUrl: config.backgroundUrl,
      backgroundUrls: config.backgroundUrls || [],
      backgroundIds: config.backgroundIds || [],
      backgroundColor: config.backgroundColor,
      backgroundFit: config.backgroundFit,
      backgroundPlayStyle: config.backgroundPlayStyle,
      width: config.width,
      height: config.height,
      isCaption: config.isCaption,
      one_to_one: config.one_to_one,
      resolution: `${config.width}x${config.height}`
    }
  }

  // 初始化多背景列表
  multiBackgrounds.value = [];

  if (config.backgroundUrls && config.backgroundUrls.length > 0) {
    // 从配置中加载多背景
    for (let i = 0; i < config.backgroundUrls.length; i++) {
      multiBackgrounds.value.push({
        id: config.backgroundIds && i < config.backgroundIds.length ? config.backgroundIds[i] : '',
        url: config.backgroundUrls[i]
      });
    }
  } else if (config.backgroundUrl) {
    // 兼容旧版，从单一背景转换
    multiBackgrounds.value.push({
      id: config.backgroundId || '',
      url: config.backgroundUrl
    });
  }

  // 加载多数字人配置详情
  const configDetail = await configStore.getMultiAvatarConfig(configId)

  // 初始化数字人配置列表
  if (configDetail.avatarConfigs && configDetail.avatarConfigs.length > 0) {
    // 使用map创建新数组避免引用问题
    multiAvatarConfigs.value = configDetail.avatarConfigs.map(avatarConfig => ({
      avatarId: avatarConfig.avatarId || '',
      voiceId: avatarConfig.voiceId || '',
      xOffset: avatarConfig.xOffset !== undefined ? avatarConfig.xOffset : 0.03,
      yOffset: avatarConfig.yOffset !== undefined ? avatarConfig.yOffset : 0.13,
      scale: avatarConfig.scale !== undefined ? avatarConfig.scale : 1.4,
      avatar: avatarConfig.avatar || null,
      voice: avatarConfig.voice || null
    }))

  } else {
    // 没有数字人配置，添加一个默认的
    addAvatarConfig()
  }
}


// 加载虚拟人物信息
const loadAvatarInfo = async (avatarId) => {
  if (!avatarId) return null

  try {
    // 先从已加载的列表中查找
    let avatar = avatarStore.avatars.find(a => a.avatarId === avatarId)

    // 如果没有找到，尝试重新获取数据
    if (!avatar) {
      await avatarStore.fetchById(avatarId)
      avatar = avatarStore.avatar
    }

    if (!avatar) {
      ElMessage.warning('未找到相关虚拟人物信息')
      return null
    }

    return avatar
  } catch (error) {
    console.error('Load avatar info failed:', error)
    return null
  }
}

// 加载语音信息
const loadVoiceInfo = async (voiceId) => {
  if (!voiceId) return null

  try {
    // 先从已加载的列表中查找
    let voice = voiceStore.voices.find(v => v.voiceId === voiceId)

    // 如果没有找到，尝试重新获取数据
    if (!voice) {
      await voiceStore.fetchVoiceById(voiceId)
      voice = voiceStore.voice
    }

    if (!voice) {
      ElMessage.warning('未找到相关语音信息')
      return null
    }

    return voice
  } catch (error) {
    console.error('Load voice info failed:', error)
    return null
  }
}

// 验证音频URL是否有效
const isValidAudioUrl = (url) => {
  if (!url) return false

  try {
    new URL(url)
    return true
  } catch (e) {
    console.error('Invalid audio URL:', e)
    return false
  }
}

// 音频播放结束
const handleAudioEnd = () => {
  isPlaying.value = false
  if (audioPlayer.value) {
    audioPlayer.value.src = '' // 清除音频源
  }
}

// 停止音频播放
const stopAudio = () => {
  if (audioPlayer.value) {
    audioPlayer.value.pause()
    audioPlayer.value.src = '' // 清除音频源
    isPlaying.value = false
  }
}

// 更新试听语音方法
const handlePreviewVoice = async () => {
  if (!currentVoice.value?.previewAudio) {
    ElMessage.warning('暂无试听音频')
    return
  }

  // 如果当前正在播放，则停止播放
  if (isPlaying.value) {
    stopAudio()
    return
  }

  // 验证音频URL
  if (!isValidAudioUrl(currentVoice.value.previewAudio)) {
    ElMessage.error('无效的音频文件地址')
    return
  }

  try {
    // 设置音频源并播放
    audioPlayer.value.src = currentVoice.value.previewAudio
    await audioPlayer.value.play()
    isPlaying.value = true
  } catch (err) {
    console.error('Audio playback failed:', err)
  }
}

// 预览
const handlePreview = (currentAvatar) => {
  if (!currentAvatar.previewVideoUrl) {
    ElMessage.warning('暂无预览视频')
    return
  }
  previewDialog.videoUrl = currentAvatar.previewVideoUrl
  previewDialog.visible = true
}

// 验证多数字人配置
const validateMultiAvatarConfigs = () => {
  if (multiAvatarConfigs.value.length === 0) {
    ElMessage.warning('请至少添加一个数字人配置')
    return false
  }
  return true
}

// 确认提交
const handleConfirm = async () => {
  if (configMode.value === 'single') {
    if (!singleFormRef.value) return

    try {
      await singleFormRef.value.validate()

      if (saveAsConfig.value) {
        const configData = {
          id: singleForm.value.id,
          name: singleForm.value.name,
          avatarId: singleForm.value.avatarId,
          voiceId: singleForm.value.voiceId,
          xOffset: singleForm.value.xOffset,
          yOffset: singleForm.value.yOffset,
          scale: singleForm.value.scale,
          backgroundType: singleForm.value.backgroundType,
          backgroundId: singleForm.value.backgroundId,
          backgroundColor: singleForm.value.backgroundColor,
          backgroundUrl: singleForm.value.backgroundUrl,
          backgroundFit: singleForm.value.backgroundFit,
          backgroundPlayStyle: singleForm.value.backgroundPlayStyle,
          width: singleForm.value.width,
          height: singleForm.value.height,
          isDefault: singleForm.value.isDefault,
          isCaption: singleForm.value.isCaption,
        }
        await configStore.saveVideoConfig(configData)
      }

      // 触发确认事件
      emit('confirm', {
        mode: 'single',
        config: {
          id: singleForm.value.id,
          avatarId: singleForm.value.avatarId,
          voiceId: singleForm.value.voiceId,
          xOffset: singleForm.value.xOffset,
          yOffset: singleForm.value.yOffset,
          scale: singleForm.value.scale,
          backgroundType: singleForm.value.backgroundType,
          backgroundId: singleForm.value.backgroundId,
          backgroundColor: singleForm.value.backgroundColor,
          backgroundUrl: singleForm.value.backgroundUrl,
          backgroundFit: singleForm.value.backgroundFit,
          backgroundPlayStyle: singleForm.value.backgroundPlayStyle,
          width: singleForm.value.width,
          height: singleForm.value.height,
          isCaption: singleForm.value.isCaption,
        }
      })

      dialogVisible.value = false
    } catch (error) {
      console.error('Form validation failed:', error)
    }
  } else {
    // 多数字人模式验证
    if (!validateMultiAvatarConfigs()) {
      return
    }

    // 提交多数字人配置
    emit('confirm', {
      mode: 'multiple',
      commonConfig: {
        backgroundType: multiCommonForm.value.backgroundType,
        backgroundId: multiCommonForm.value.backgroundId,
        backgroundUrl: multiCommonForm.value.backgroundUrl,
        backgroundUrls: multiCommonForm.value.backgroundUrls,
        backgroundIds: multiCommonForm.value.backgroundIds,
        backgroundColor: multiCommonForm.value.backgroundColor,
        backgroundFit: multiCommonForm.value.backgroundFit,
        backgroundPlayStyle: multiCommonForm.value.backgroundPlayStyle,
        width: multiCommonForm.value.width,
        height: multiCommonForm.value.height,
        isCaption: multiCommonForm.value.isCaption,
        one_to_one: multiCommonForm.value.one_to_one,
      },
      avatarConfigs: multiAvatarConfigs.value.map(config => ({
        avatarId: config.avatarId,
        voiceId: config.voiceId,
        xOffset: config.xOffset,
        yOffset: config.yOffset,
        scale: config.scale,
      }))
    })

    dialogVisible.value = false
  }
}

// 重置表单
const resetForm = () => {
  // 重置单数字人模式表单
  if (singleFormRef.value) {
    singleFormRef.value.resetFields()
  }

  if (multiCommonFormRef.value) {
    multiCommonFormRef.value.resetFields()
  }

  // 重置为初始值
  singleForm.value = {
    id: null,
    name: '',
    avatarId: '',
    voiceId: '',
    xOffset: 0.03,
    yOffset: 0.13,
    scale: 1.4,
    backgroundType: 'color',
    backgroundId: '',
    backgroundColor: '#f6f6fc',
    backgroundUrl: '',
    backgroundFit: 'crop',
    backgroundPlayStyle: 'loop',
    width: 1080,
    height: 1920,
    isDefault: false,
    isCaption: false,
    resolution: '1080x1920',
  }

  // 重置多数字人模式表单
  multiCommonForm.value = {
    backgroundType: 'color',
    backgroundId: '',
    backgroundUrl: '',
    backgroundUrls: [],
    backgroundIds: [],
    backgroundColor: '#f6f6fc',
    backgroundFit: 'crop',
    backgroundPlayStyle: 'loop',
    width: 1080,
    height: 1920,
    isCaption: false,
    one_to_one: true,
    resolution: '1080x1920'
  }

  multiBackgrounds.value = []; // 清空多背景列表
  multiAvatarConfigs.value = []

  // 重置其他状态
  currentAvatar.value = null
  currentVoice.value = null
  saveAsConfig.value = false
  selectedConfigId.value = ''
  selectedMultiConfigId.value = ''
}

// 初始化
onMounted(init)

// 监听背景库弹窗显示状态
watch(showBackgroundGallery, (value) => {
  if (value) {
    // 当弹窗打开时，重新获取背景库数据
    backgroundStore.getBackgrounds({
      page: 1,
      pageSize: 12,
      type: singleForm.value.backgroundType
    })
  }
})

// 监听多数字人模式下背景库弹窗显示状态
watch(showMultiBackgroundGallery, (value) => {
  if (value) {
    // 当弹窗打开时，重新获取背景库数据
    backgroundStore.getBackgrounds({
      page: 1,
      pageSize: 12,
      type: multiCommonForm.value.backgroundType
    })
  }
})
</script>

<style scoped>
/* Mode Selection Container */
.mode-selection-container {
  text-align: center;
  align-items: center;
  margin-bottom: 20px;
}

.info-icon {
  margin-left: 8px;
  color: #909399;
  cursor: pointer;
}

/* Preview styles */
.select-preview {
  display: flex;
  align-items: center;
}

.preview-content {
  display: flex;
  align-items: center;
  margin-right: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 8px;
  background-color: #f5f7fa;
  flex: 1;
}

.preview-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  object-fit: cover;
}

.image-placeholder {
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f0f2f5;
  border-radius: 4px;
  color: #909399;
  font-size: 24px;
}

.preview-info {
  display: flex;
  flex-direction: column;
  margin-left: 10px;
  flex: 1;
}

.preview-tags {
  margin-top: 5px;
  display: flex;
  gap: 5px;
}

.avatar-actions {
  display: flex;
  justify-content: center;
}

/* Config option */
.config-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

/* Avatar config form */
.avatar-config-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.config-row {
  display: flex;
  align-items: center;
}

.config-label {
  width: 120px;
  font-size: 14px;
  color: #606266;
}

.avatar-config-tip {
  margin-top: 16px;
}

/* Common settings */
.common-settings {
  margin-top: 20px;
  border-top: 1px solid #ebeef5;
  padding-top: 20px;
}

/* Background resource container */
.background-resource-container {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

/* 修改背景预览容器尺寸，使其更大并保持16:9比例 */
.background-preview {
  position: relative;
  width: 320px;
  height: 180px;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 10px;
  border: 1px solid #e4e7ed;
}

/* 确保图片填满整个容器 */
.background-preview .preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.preview-video {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.remove-btn {
  position: absolute;
  top: 8px;
  right: 8px;
  z-index: 1;
  opacity: 0.9;
}

.background-actions {
  display: flex;
  gap: 10px;
}

/* Multi avatar container */
.multi-avatar-container {
  margin-top: 20px;
}

/* Avatar list container */
.avatar-list-container {
  margin-top: 20px;
}

.avatar-list-container h3 {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: 600;
}

.empty-avatar-list {
  padding: 30px 0;
}

.avatar-collapse-title {
  display: flex;
  align-items: center;
}

.content-preview {
  margin-left: 15px;
  color: #909399;
  font-size: 12px;
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* Multi background container */
.multi-background-container {
  margin-top: 10px;
}

.empty-background-tip {
  margin-bottom: 15px;
}

.background-list {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 15px;
}

/* 修改多背景模式下的背景项尺寸 */
.background-item {
  position: relative;
  width: 240px;
}

.background-item .background-preview {
  width: 100%;
  height: 135px;
}

.background-index {
  text-align: center;
  margin-top: 5px;
  font-size: 12px;
  color: #606266;
}

.add-background-container {
  display: flex;
  gap: 10px;
  margin-top: 15px;
}

/* Dialog footer */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

/* Preview dialog */
.preview-dialog .preview-video {
  max-width: 100%;
  border-radius: 4px;
}

/* Responsive adjustments */
@media screen and (max-width: 768px) {
  .select-preview {
    flex-direction: column;
    align-items: flex-start;
  }

  .preview-content {
    width: 100%;
    margin-bottom: 10px;
    margin-right: 0;
  }

  .background-preview {
    width: 100%;
    height: 0;
    padding-bottom: 56.25%; /* 16:9比例 */
  }

  .background-item {
    width: 100%;
  }

  .background-actions {
    flex-direction: column;
    width: 100%;
  }

  .add-background-container {
    flex-direction: column;
  }
}

/* Additional utility classes */
.ml-3 {
  margin-left: 12px;
}

.mt-2 {
  margin-top: 8px;
}
</style>